//
//  ViewController.swift
//  makeCalader
//
//  Created by ning on 2018/1/10.
//  Copyright © 2018年 ning. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var backStepButton: UIButton!
    @IBOutlet weak var nextStepButton: UIButton!

    @IBOutlet weak var calendarCollectionView: UICollectionView!
    
    @IBOutlet weak var calendarCollectionViewFlowLayout: UICollectionViewFlowLayout!
    
    @IBOutlet weak var currentDateLabel: UILabel!
    
    var itemSize = CGSize(width:(UIScreen.main.bounds.width - 10 * 2) / 7,height:(UIScreen.main.bounds.width - 10 * 2) / 7)
    
    var selectArr = [String]()
    var startItem: String?//被选择的元素
    var endItem: String?
    var currentDate = Date()
    var date = Date()
    var days  = 0
    var dateArray = [String]()
    var currentCom:DateComponents?
    var currentDateStr:String?

    var didSelectCalanderBlock:((_ dateString:String,_ dateCom:DateComponents) -> ())?//选择日期
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
     setupCollectionView()
     setupView()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func didStepButtonTouchUpInside(_ sender: UIButton) {
        if sender === backStepButton  {
            lastAction()
        }else if sender === nextStepButton {
            nextAction()
        }
    }
    
}

extension ViewController {
    func setupView() {
        backStepButton.layer.cornerRadius = backStepButton.frame.width / 2
        nextStepButton.layer.cornerRadius = nextStepButton.frame.width / 2
    }
    func setupCollectionView() {
        calendarCollectionView.delegate = self
        calendarCollectionView.dataSource = self
        calendarCollectionViewFlowLayout.itemSize = itemSize
        self.calendarCollectionView.register(DateCollectionViewCell.self, forCellWithReuseIdentifier: DateCollectionViewCell.className)
        self.calendarCollectionView.register(WeekCollectionViewCell.self, forCellWithReuseIdentifier: WeekCollectionViewCell.className)
        self.currentDateLabel.text = String(format: "%li-%.2ld", NCalendarDate.getYear(date: self.date), NCalendarDate.getMonth(date: self.date))
        currentCom = (Calendar.current as NSCalendar).components([NSCalendar.Unit.year, NSCalendar.Unit.month, NSCalendar.Unit.day], from: self.date)
        currentDateStr = String(format: "%li-%.2ld-%.2ld", NCalendarDate.getYear(date: self.date), NCalendarDate.getMonth(date: self.date),NCalendarDate.getDay(date: date))
        dateArray = ["日","一","二","三","四","五","六"]
    }
    
}


extension ViewController {
    func lastAction() {
        UIView.transition(with: calendarCollectionView, duration: 0.5, options: .transitionCurlDown, animations: {
            self.date = NCalendarDate.getLastMonth(date: self.date)
            self.currentDateLabel.text = String(format:"%li-%.2ld",NCalendarDate.getYear(date: self.date),NCalendarDate.getMonth(date: self.date))
        }, completion: nil)
        calendarCollectionView.reloadData()
    }
    
    func nextAction() {
        UIView.transition(with: calendarCollectionView, duration: 0.5, options: .transitionCurlUp, animations: {
            self.date = NCalendarDate.getNextMonth(date: self.date)
            self.currentDateLabel.text = String(format:"%li-%.2ld",NCalendarDate.getYear(date: self.date),NCalendarDate.getMonth(date: self.date))
        }, completion: nil)
        calendarCollectionView.reloadData()
    }
    func reloadView() {
        
    }
}

extension ViewController: UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    
    @objc(numberOfSectionsInCollectionView:) func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 2
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        switch section {
        case 0:
            return dateArray.count
        default:
            let days = NCalendarDate.getDaysInThisMonth(date: date)
            let firstWeek = NCalendarDate.getFirstWeekInThisMonth(date: date)
            let day = days + firstWeek
            let residue = day % 7
            let num = residue != 0  ? 7 - residue : 0
            return day + num
        }
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
      
        switch indexPath.section {
        case 0:
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: WeekCollectionViewCell.className, for: indexPath) as! WeekCollectionViewCell
            cell.timeLabel.text = dateArray[(indexPath as NSIndexPath).row]
            cell.timeLabel.textColor = UIColor.lightGray
            return cell
            
        default:
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NCalendarCollectionViewCell.className, for: indexPath) as! NCalendarCollectionViewCell
        cell.setupView()
        let days = NCalendarDate.getDaysInThisMonth(date: date)
        let week = NCalendarDate.getFirstWeekInThisMonth(date: date)
    
        var day = 0
        let index = indexPath.row
        
        if index < week {
            let lastMonthDays = NCalendarDate.getDaysInLastMonth(date: date)
            let lastDate = NCalendarDate.getLastMonth(date: date)
            let dayInLastMonth = lastMonthDays - (week - index) + 1
            cell.dateButton.setTitle(String(dayInLastMonth), for: .normal)
            cell.dateStr = String(format:"%li-%.2ld-%.2ld",NCalendarDate.getYear(date: lastDate),NCalendarDate.getDay(date: lastDate),dayInLastMonth)
            cell.date = NCalendarDate.getSomeDayDate(day: dayInLastMonth, date: lastDate)
            cell.dateComponents = (Calendar.current as NSCalendar).components([NSCalendar.Unit.year, NSCalendar.Unit.month, NSCalendar.Unit.day], from: cell.date ?? Date())
  
        } else if index > week + days - 1 {
            let nextDate = NCalendarDate.getNextMonth(date:date)
            let dayInNextMonth = index - (week + days - 1)
            cell.dateButton.setTitle(String(dayInNextMonth), for: .normal)
            cell.dateStr = String(format:"%li-%.2ld-%.2ld",NCalendarDate.getYear(date: nextDate),NCalendarDate.getDay(date: nextDate),dayInNextMonth)
            cell.date = NCalendarDate.getSomeDayDate(day: dayInNextMonth, date: nextDate)
            cell.dateComponents = (Calendar.current as NSCalendar).components([NSCalendar.Unit.year, NSCalendar.Unit.month, NSCalendar.Unit.day], from: cell.date ?? Date())
        }else {
                day = index - week + 1
                cell.dateButton.setTitle(String(day), for: .normal)
                let da = Date()
                let com = (Calendar.current as NSCalendar).components([NSCalendar.Unit.year, NSCalendar.Unit.month, NSCalendar.Unit.day], from: da)
                
                let abc = String(format: "%li-%.2ld", com.year ?? 0, com.month ?? 0)
                cell.dateStr = String(format:"%li-%.2ld-%.2ld",NCalendarDate.getYear(date: self.date),NCalendarDate.getMonth(date: self.date),day)
                cell.date = NCalendarDate.getSomeDayDate(day: day, date: date)
                cell.dateComponents = (Calendar.current as NSCalendar).components([NSCalendar.Unit.year, NSCalendar.Unit.month, NSCalendar.Unit.day], from: cell.date ?? Date())
                if self.currentDateLabel.text! == abc {
                    if cell.dateButton.titleLabel?.text == String(NCalendarDate.getDay(date: date)) {
                        cell.backgroundColor = UIColor.cyan
                    } else {
                        cell.backgroundColor = UIColor.white
                    }
                } else {
                    cell.backgroundColor = UIColor.white
                }
            }

        
        
        let start:String = startItem ?? ""
        let dateCom = (Calendar.current as NSCalendar).components([NSCalendar.Unit.year, NSCalendar.Unit.month, NSCalendar.Unit.day], from: date)
        
        if start == cell.dateStr && start.count > 0 {
            cell.dateButton.backgroundColor = .blue
            cell.dateButton.setTitleColor(.white, for: .normal)
        }else if  dateCom.month != cell.dateComponents?.month && dateCom.month != 0 {
            cell.dateButton.backgroundColor = .clear
            cell.dateButton.setTitleColor(.lightGray, for: .normal)
        }else{
            cell.dateButton.backgroundColor = .clear
            cell.dateButton.setTitleColor(UIColor.darkGray, for: .normal)
        }
        
        cell.dateButton.isEnabled = NCalendarDate.compareDateAndAnother(dateA: currentDate, dateB: cell.date ?? Date())  != -1 ? true : false
        cell.didDateButtonTapBlock = { [weak self] in
            self?.startItem = cell.dateStr
            collectionView.reloadData()
            self?.didSelectCalanderBlock?(cell.dateStr ?? "",cell.dateComponents ?? DateComponents())
            print(cell.dateStr ?? "")
        }
        return cell
            
        }
        
       
    }
   
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print(indexPath.row)
        collectionView.deselectItem(at: indexPath, animated: true)
        let cell = collectionView.cellForItem(at: indexPath) as! NCalendarCollectionViewCell
        self.didSelectCalanderBlock?(cell.dateStr ?? "",cell.dateComponents ?? DateComponents())
        print(cell.dateStr ?? "")
    }
}

extension NSObject {
    static var className: String { return String(describing: self) }
    var className: String { return String(describing: self) }
}
